package com.cloud.pole.common.util;

/**
 * @Author: Frank Chen
 * @Date: 2019/11/20 11:46
 */

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class HttpURLConUtils {
    public static final String charsetName = "UTF-8";

    public static String doGet(String strUrl) {
        return doGet(strUrl, null);
    }
    /**
     * get
     * @param strUrl
     * @param headers
     * @return
     */
    public static String doGet(String strUrl, Map<String, String> headers) {
        HttpURLConnection connection = null;
        String out = null;
        InputStream inputStream = null;
        try {
            URL _url = new URL(strUrl);
            // 打开连接
            connection = (HttpURLConnection) _url.openConnection();
            // 设置请求方式：get请求
            connection.setRequestMethod("GET");
            // 设置超时时间，单位毫秒：5秒
            connection.setConnectTimeout(5000);
            // 设置读取远程服务器时间，单位毫秒：10秒
            connection.setReadTimeout(10000);
            // 设置请求头
            if (headers != null) {
                for (String headName : headers.keySet()) {
                    String headValue = headers.get(headName);
                    connection.setRequestProperty(headName, headValue);
                }
            }
            // 发送请求
            connection.connect();
            // 通过connection获取输入流数据
            if (connection.getResponseCode() == 200) {
                inputStream = connection.getInputStream();
                out = inToString(inputStream);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            close(inputStream);
            // 关闭连接
            connection.disconnect();
        }
        return out;
    }

    /**
     * post
     * @param strUrl
     * @param params
     * @param headers
     * @return
     */
    public static String doPost(String strUrl, String params, Map<String, String> headers) {
        HttpURLConnection connection = null;
        String out = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            URL _url = new URL(strUrl);
            // 打开连接
            connection = (HttpURLConnection) _url.openConnection();
            // 设置请求方式：get请求
            connection.setRequestMethod("POST");
            // 设置超时时间，单位毫秒：5秒
            connection.setConnectTimeout(5000);
            // 设置读取远程服务器时间，单位毫秒：10秒
            connection.setReadTimeout(10000);
            // 设置请求头
            if (headers != null) {
                for (String headName : headers.keySet()) {
                    String headValue = headers.get(headName);
                    connection.setRequestProperty(headName, headValue);
                }
            }
            // 默认值为：true，当前向远程服务读取数据时，设置为true，该参数可有可无
            connection.setDoInput(true);
            if (params != null) {
                // 默认值为：false，当向远程服务器传送数据/写数据时，需要设置为true
                connection.setDoOutput(true);
                outputStream = connection.getOutputStream();
                outputStream.write(params.getBytes(charsetName));
            }
            // 发送请求
            connection.connect();
            // 通过connection获取输入流数据
            if (connection.getResponseCode() == 200) {
                inputStream = connection.getInputStream();
                out = inToString(inputStream);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            close(outputStream);
            close(inputStream);
            // 关闭连接
            connection.disconnect();
        }
        return out;
    }

    public static String doPost(String strUrl) {
        return doPost(strUrl, null, null);
    }
    //ByteArrayOutputStream无需关闭
    private static String inToString(InputStream inputStream) throws IOException {
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            result.write(buffer, 0, length);
        }
        String str = result.toString(charsetName);
        return str;
    }

    private static void close(Closeable closeable) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String result = doGet("https://blog.csdn.net/zhangsweet1991");
        System.out.println(result);
    }
}
